#coding:utf-8

from dagou.Agent import ConfigObj
from dagou.MainFrame import xrcdagou
from dagou.sites import JD, TaobaoAgent, amazon, suning
import dagou.Form as Form
import os
import sys
import threading
import time
import wx
import wx.lib.mixins.listctrl  as  listmix
sys.path.append('.')
# import stat
# import dagou.HtmlParser as HtmlParser


class TestListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
    def __init__(self):
#         wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        
        # Add these lines verbatim
        p = wx.PreListCtrl()   # Call the function PreXXX where XXX is your wx base class
        self.PostCreate(p)
        self.Bind(wx.EVT_WINDOW_CREATE, self.OnCreate)  # When the panel is really created, notify me so I can do my initialization
        self.itemDataMap = {}
   
    def OnCreate(self, event):
        self.Unbind(wx.EVT_WINDOW_CREATE)
        # Do all of your normal initialization here
        listmix.ListCtrlAutoWidthMixin.__init__(self)      
        listmix.ColumnSorterMixin.__init__(self, 8)
        
    def GetListCtrl(self):
        return self  
        
    def InsertResult(self, result):
        if result is None:
            return
        itemstr = (result.site, result.name, '%06d' %result.totalprice, 
                '%06d' %result.price, '%03d' %result.carriage, '%05d' %result.volume, 
                result.link, result.store, result.time)
                
        item = (result.site, result.name, str(result.totalprice), 
                str(result.price), str(result.carriage), str(result.volume), 
                result.link, result.store, result.time)        

        index = self.InsertStringItem(sys.maxint, item[0])
        for col, text in enumerate(item[1:]):
            self.SetStringItem(index, col+1, text)
            
        self.SetItemData(index, index)#　关联数据和映射
        self.itemDataMap[index] = itemstr

class FormManager(object):
    formPath = "forms"
    dealedFormPath = "dealed"
    formScanInterval = 600
    formList = []
    formId = 0
#     procFormThreadNum = 5
    agentList = []
    priForm = None
    priFormCount = 0
    priProcTimeout = 15000
    
    def __init__(self):
        self.formPath = os.getcwd() + os.sep + self.formPath
        print(self.formPath)
        self.agentList.append(TaobaoAgent.TaobaoAgent())
        self.agentList.append(JD.JD())
        self.agentList.append(amazon.Amazon())
        self.agentList.append(suning.Suning())

    def ScanForms(self):
        print("扫描新订单………………")
#         for evefile in os.listdir(self.formPath):
#             subpath = os.path.join(self.formPath, evefile)
#             mode = os.stat(subpath)[stat.ST_MODE]
#             if stat.S_ISDIR(mode):
#                 continue
#             reverse = evefile[::-1]
#             if (reverse.find("lmth.") != 0):
#                 continue
#             f = open(subpath,'r')
#             parser = HtmlParser.MyHTMLParser()
#             parser.feed(f.read())
#             f.close()
#             newForm = Form.Form()
#             newForm.name = parser.item.GetItem(1,"html").GetItem(1,"table").GetItem(1,"tr").GetItem(2,"td").data.decode('gbk')
#             newForm.model = parser.item.GetItem(1,"html").GetItem(1,"table").GetItem(2,"tr").GetItem(2,"td").data.decode('gbk')
#             newForm.price = parser.item.GetItem(1,"html").GetItem(1,"table").GetItem(3,"tr").GetItem(2,"td").data.decode('gbk')
#             newForm.description = parser.item.GetItem(1,"html").GetItem(1,"table").GetItem(4,"tr").GetItem(2,"td").data.decode('gbk')
#             #下面为订单添加Agent
#             yes = '是'
#             yes = yes.decode('utf-8')
#             if cmp(parser.item.GetItem(1,"html").GetItem(1,"table").GetItem(6,"tr").GetItem(2,"td").data.decode('gbk'),yes) == 0:
#                 newForm.agentIds.append(2)
#             newForm.agentIds.append(3)
#             self.formList.append(newForm)
#             os.remove(subpath)
#             print "增加新订单："
#             print "商品名称：",newForm.name
#             print "商品型号：",newForm.model
#             print "商品价格：",newForm.price
#             print "商品描述：",newForm.description
#             print "是否搜索淘宝：",(2 in newForm.agentIds)
        print "新订单扫描结束！"
        
    def AddForm(self, newForm):
        if ConfigObj.ForAdmin:
            self.formList.append(newForm)
        print "增加新订单："
        print "商品名称：",newForm.name
        print "商品型号：",newForm.model
        print "商品价格：",newForm.price
        print "商品描述：",newForm.description
        print "是否搜索淘宝：",(2 in newForm.agentIds)
        
    def AddPriForm(self, newForm):
        newForm.pri = Form.PRI_URGENT
        if ConfigObj.ForAdmin:
            self.formList.append(newForm)
        self.priForm = newForm
        print "增加立即处理订单："
        print "商品名称：",newForm.name
        print "商品型号：",newForm.model
        print "商品价格：",newForm.price
        print "商品描述：",newForm.description
        print "是否搜索淘宝：",(2 in newForm.agentIds)
        
        for a in self.agentList:
            self.priFormCount += 1
            a.que.put((Form.PRI_URGENT, newForm))
        
        wx.CallLater(self.priProcTimeout, wx.GetApp().GetTopWindow().OnMenu_Refresh, None)
    
    def Run(self):
#         i = 1
#         while i <= self.procFormThreadNum:
#             thread.start_new_thread(self.StartProcForms,(i,0))
#             i = i + 1

        for i in self.agentList:
            i.setDaemon(True)
            i.start()
            
        while True:
            self.ScanForms()
            for a in self.agentList:
                for af in self.formList:
                    a.que.put((Form.PRI_NORMAL, af))
                    
            time.sleep(self.formScanInterval)

#     def StartProcForms(self,threadId,_p):
#         agentId = 0
#         while 1:
#             if self.agentList.__len__() == 0:
#                 time.sleep(300)
#                 continue
#             if self.agentList[agentId].curThread != 0:
#                 agentId = (agentId + 1) % self.agentList.__len__()
#                 if agentId == 0:
#                     time.sleep(10)
#                 continue
#             self.agentList[agentId].curThread = threadId
#             for form in self.formList:
#                 self.agentList[agentId].GetSearchList(form)
#             self.agentList[agentId].curThread = 0
#             agentId = (agentId + 1) % self.agentList.__len__()
#             if agentId == 0:
#                 time.sleep(100)            
#             time.sleep(30)
        
        
class dagouWinApp(wx.App):
    def __init__(self, formmanager, redirect=False, filename=None,
                useBestVisual=False, clearSigInt=True):
        super(dagouWinApp, self).__init__(redirect, filename, useBestVisual, clearSigInt)
        self.fm = formmanager
        
    def OnInit(self):        
        self.frame = xrcdagou(None)
        bmp = wx.Image("111.jpg").ConvertToBitmap()
        wx.SplashScreen(bmp, 
                wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
                1000, None, -1)
        wx.Yield()        
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True
        
if __name__ == '__main__':
#     f = Form.Form()
#     f.name = '大王纸尿裤'
#     f.model = ''
#     f.price = 2500
#     f.description = '白色的'
    ConfigObj.LoadCfg()
    fm = FormManager()
#     fm.AddForm(f)

    winapp = dagouWinApp(fm)

    fmThread = threading.Thread(target=fm.Run)
    fmThread.setDaemon(True)
    fmThread.start()
    
    winapp.MainLoop()
